<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="平台" v-bind="validateInfos.platform">
            <j-dict-select-tag v-model:value="formData.platform" :showChooseOption="false" dictCode="platform" placeholder="请选择平台" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="类型" v-bind="validateInfos.type">
            <j-dict-select-tag
              allowClear
              :disabled="disabled"
              placeholder="请选择类型"
              v-model:value="formData.type"
              :showChooseOption="false"
              dictCode="book_rec_type"
              @change="typeChange"
              :stringToNumber="true"
            />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="小说图片" v-bind="validateInfos.picUrl" v-if="isShowFile">
            <j-image-upload :fileSize="250" v-model:value="formData.picUrl" :disabled="disabled" @change="upPic" />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="内容" v-bind="validateInfos.contentType" v-if="isShowFile">
            <a-select
              v-model:value="formData.contentType"
              @change="handleChange"
            >
              <a-select-option :value="0">小说</a-select-option>
              <a-select-option :value="1">H5</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="!isShowFile||(isShowFile&&formData.contentType===0)">
          <a-form-item label="小说ID" v-bind="validateInfos.bookId">
            <a-input v-model:value="formData.bookId" placeholder="请输入小说ID" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.contentType===1">
          <a-form-item label="H5链接" v-bind="validateInfos.h5Url">
            <a-input v-model:value="formData.h5Url" placeholder="请输入H5链接" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="排序号" v-bind="validateInfos.sort">
            <a-input-number v-model:value="formData.sort" placeholder="请输入排序号" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>

      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JDictSelectTag from '@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../BookSetting.api';
  import { Form } from 'ant-design-vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    bookId: undefined,
    sort: undefined,
    type: undefined,
    picUrl: '',
    platform: '',
    contentType:0,
    h5Url: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const validateH5 = async (rule, value) => {
    if (value === '') {
      return Promise.reject('请输入H5链接!');
    } else {
      let flag
      if (formData.platform===0){
        flag=value.startsWith('https://www.novelshome.com')
      }else if (formData.platform===1){
        flag=value.startsWith('https://www.novelworm.com')
      }else{
        flag=value.startsWith('https://www.vermenovela.com')
      }
      if (flag){
        return Promise.resolve();
      }else {
        return Promise.reject('请输入平台域名!');
      }
    }
  };

  //表单验证
  const validatorRules = {
    bookId: [{ required: true, message: '请输入小说id!' }],
    sort: [{ required: true, message: '请输入排序号!' }],
    type: [{ required: true, message: '请选择类型!' }],
    platform: [{ required: true, message: '请选择平台!' }],
    picUrl: [{ required: true, message: '请选择图片!' }],
    contentType: [{ required: true, message: '请选择图片!' }],
    h5Url: [{ required: true,validator: validateH5 }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    //重置表单
    nextTick(() => {
      resetFields();
      setTimeout(() => {
        typeChange(record.type);
        //赋值
        Object.assign(formData, record);
      }, 2);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    let arr=['platform','type','sort']
    if (isShowFile.value){
        if (formData.contentType===0){
          arr.push('bookId')
        }else {
          arr.push('h5Url')
        }
      arr.push('picUrl')
      arr.push('contentType')
    }else {
      arr.push('bookId')
    }
    // 触发表单验证
    await validate(arr);
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
        nextTick(() => {
          resetFields();
        });
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  async function upPic(val) {
    formData.posterUrl = val;
  }

  const isShowFile = ref(false);

  function typeChange(val) {
    isShowFile.value = val < 1;
    if (!isShowFile.value) {
      formData.posterUrl = '';
    }
  }

  function clearForm() {
    let obj = { id: '', bookId: undefined, sort: undefined, type: undefined, picUrl: '' };
    Object.assign(formData, obj);
  }

  defineExpose({
    add,
    edit,
    submitForm,
    clearForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
